using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.IO;
using System.Configuration;

namespace Instedd.Labs.FeedPoster
{
    public partial class Form1 : Form
    {
        const int BUFFER_SIZE = 4096;
        bool isStarted = false;

        Thread runningThread;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            runningThread = new Thread(new ThreadStart(PostFeeds));
            runningThread.Start();
            btnStart.Enabled = false;
            btnStop.Enabled = true;
        }

        private void PostFeeds()
        {
            int postInterval = Int32.Parse(ConfigurationManager.AppSettings["postInterval"]) * 1000;
            while (true)
            {
                PostFeed(ConfigurationManager.AppSettings["localPathToKmlFile"], new Uri(ConfigurationManager.AppSettings["remoteUrlToKmlFeed"]));
                PostFeed(ConfigurationManager.AppSettings["localPathToGeoRssFile"], new Uri(ConfigurationManager.AppSettings["remoteUrlToGeoRssFeed"]));
                Thread.Sleep(postInterval);
            }
        }

        void LogMessage(String message)
        {
            lbOutput.Items.Add(String.Format("{0} - {1}",DateTime.Now, message));
        }

        private void PostFeed(String fileToPost, Uri targetUrl)
        {
            LogMessage(String.Format("Tyring to post {0} to {1}", fileToPost, targetUrl));

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(targetUrl.ToString());

            if (!File.Exists(fileToPost))
            {
                LogMessage(String.Format("ERROR: File {0} not found",fileToPost));
                return;
            }

            request.Method = "POST";
            request.ContentType = "application/xml";
            FileInfo fi = new FileInfo(fileToPost);
            request.ContentLength = fi.Length;

            HttpWebResponse response = null;

            try
            {
                Stream requestStream = request.GetRequestStream();
                long bufferSize = request.ContentLength < BUFFER_SIZE ? request.ContentLength : BUFFER_SIZE;
                byte[] buffer = new Byte[bufferSize];
                int bytesRead = 0;

                using (FileStream fileStream = new FileStream(fileToPost,
                            FileMode.Open, FileAccess.Read))
                {
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        requestStream.Write(buffer, 0, bytesRead);
                    }
                }
                response = request.GetResponse() as HttpWebResponse;
            }
            catch (Exception ex)
            {
                LogMessage(String.Format("ERROR: {0}", ex.Message));
                return;
            }

            LogMessage(String.Format("OK: {0} posted successfully",fileToPost));
            return;
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            runningThread.Abort();
            btnStop.Enabled = false;
            btnStart.Enabled = true;
        }
    }
}